<template>
  <div class="dashboard-container" :class="{ 'light-theme': themeStore.isLight }">
    <!-- 数据概览卡片区 -->
    <el-row :gutter="24" class="overview-row">
      <el-col :span="8">
        <div class="stat-card primary-gradient">
          <div class="stat-icon"><el-icon><PictureFilled /></el-icon></div>
          <div class="stat-info">
            <div class="stat-value">{{ totalWorks }}</div>
            <div class="stat-label">总照片数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="stat-card success-gradient">
          <div class="stat-icon"><el-icon><User /></el-icon></div>
          <div class="stat-info">
            <div class="stat-value">{{ totalUsers }}</div>
            <div class="stat-label">用户数</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 管理区卡片 -->
    <el-row :gutter="24" class="manage-row">
      <el-col :span="8">
        <div class="manage-card review-card">
          <div class="manage-icon"><el-icon><Timer /></el-icon></div>
          <div class="manage-info">
            <div class="manage-title">待审核作品</div>
            <div class="manage-value">{{ pendingWorks }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="manage-card publish-card">
          <div class="manage-icon"><el-icon><CircleCheck /></el-icon></div>
          <div class="manage-info">
            <div class="manage-title">已发布作品</div>
            <div class="manage-value">{{ publishedWorks }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="manage-card ban-card">
          <div class="manage-icon"><el-icon><Remove /></el-icon></div>
          <div class="manage-info">
            <div class="manage-title">已封禁作品</div>
            <div class="manage-value">{{ removedWorks }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 作品分类占比饼图 -->
    <el-row :gutter="24" class="chart-row">
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <div class="chart-card">
          <h3 class="chart-title">作品分类占比</h3>
          <div class="pie-container">
            <div class="pie-chart">
              <svg width="160" height="160" viewBox="0 0 160 160">
                <!-- 背景圆 -->
                <circle cx="80" cy="80" r="65" fill="#f9fafb" stroke="none" />
                <!-- 数据分段 -->
                <template v-if="categoryStats.length > 0">
                  <circle
                    v-for="(item, idx) in categoryStats"
                    :key="item.category"
                    r="65"
                    cx="80"
                    cy="80"
                    fill="none"
                    :stroke="pieColors[idx % pieColors.length]"
                    stroke-width="24"
                    :stroke-dasharray="`${Math.round(parseFloat(item.percentage) * 4.08)},408`"
                    :stroke-dashoffset="getPieOffset(idx)"
                    class="pie-segment"
                  />
                </template>
                <template v-else>
                  <circle r="65" cx="80" cy="80" fill="none" stroke="#e2e8f0" stroke-width="24" stroke-dasharray="408 0" />
                </template>
                <!-- 内圆（中心白色） -->
                <circle cx="80" cy="80" r="45" fill="white" />
                              </svg>
            </div>
            <div class="pie-legend">
              <template v-if="categoryStats.length > 0">
                <div v-for="(item, idx) in categoryStats" :key="item.category" class="legend-item">
                  <span class="color-dot" :style="`background:${pieColors[idx % pieColors.length]}`"></span>
                  <span class="category-name">{{ item.category }}</span>
                  <span class="category-percent">{{ item.percentage }}</span>
                </div>
              </template>
              <template v-else>
                <div class="no-data">暂无数据</div>
              </template>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-row :gutter="24">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <div class="recent-card">
              <h3 class="recent-title">最新评论</h3>
              <el-table 
                :data="newComments" 
                border 
                show-header="false"
                class="modern-table"
                size="small"
                :cell-class-name="tableCellClassName"
                row-class-name="modern-row"
              >
                <el-table-column prop="avatar" label="头像" width="50" min-width="50">
                  <template #default="scope">
                    <div class="image-cell">
                      <el-avatar size="28" :src="scope.row.avatar" class="table-avatar" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="username" label="用户" width="90" min-width="80">
                  <template #default="scope">
                    <div class="username-cell">{{ scope.row.username }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="content" label="评论内容" width="130" min-width="80">
                  <template #default="scope">
                    <div class="content-cell">
                      <div class="content-text">{{ scope.row.content }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="create_time" label="评论时间" width="115" min-width="100">
                  <template #default="scope">
                    <div class="time-cell">
                      <el-icon><Clock /></el-icon>
                      <span>{{ formatDate(scope.row.create_time) }}</span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <div class="recent-card">
              <h3 class="recent-title">最新注册用户</h3>
              <el-table 
                :data="newUsers" 
                border 
                show-header="false"
                class="modern-table"
                size="small"
                :cell-class-name="tableCellClassName"
                row-class-name="modern-row"
              >
                <el-table-column prop="avatar" label="头像" width="50" min-width="50">
                  <template #default="scope">
                    <div class="image-cell">
                      <el-avatar size="28" :src="scope.row.avatar" class="table-avatar" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="nickname" label="昵称" width="155" min-width="80">
                  <template #default="scope">
                    <div class="username-cell">{{ scope.row.nickname }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="register_time" label="注册时间" width="100" min-width="100">
                  <template #default="scope">
                    <div class="time-cell">
                      <el-icon><Clock /></el-icon>
                      <span>{{ formatDate(scope.row.register_time) }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="80" min-width="70">
                  <template #default="scope">
                    <div class="status-container">
                      <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'" size="small" class="status-tag" effect="light">
                        {{ scope.row.status === 0 ? '正常' : '封禁' }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { PictureFilled, User, Clock, Timer, CircleCheck, Remove} from '@element-plus/icons-vue'
import { useThemeStore } from '@/stores/theme'
import request from '@/utils/request'

// 引入主题状态
const themeStore = useThemeStore()

// 定义响应数据的状态
const totalWorks = ref(0)
const totalUsers = ref(0)
const pendingWorks = ref(0)  // 审核中(status=0)的作品
const publishedWorks = ref(0)  // 已发布(status=1)的作品
const removedWorks = ref(0)  // 已封禁(status=2)的作品
const reportedContent = ref(0)
const newUsers = ref([])  // 存储最新注册用户的数据
const newComments = ref([])  // 存储最新评论的数据

// 作品分类占比数据
const categoryStats = ref([])

// 饼图颜色
const pieColors = [
  '#6366f1', // 靛青
  '#3b82f6', // 蓝色
  '#10b981', // 绿色
  '#f59e0b', // 琥珀色
  '#ef4444', // 红色
  '#8b5cf6'  // 紫色
]

let pieOffsetCache = []
const getPieOffset = (idx) => {
  if (pieOffsetCache.length !== categoryStats.value.length) {
    // 重新计算
    let offset = 0
    pieOffsetCache = categoryStats.value.map((item) => {
      const val = Math.round(parseFloat(item.percentage) * 4.08)
      const ret = -offset
      offset += val
      return ret
    })
  }
  return pieOffsetCache[idx] || 0
}

// 格式化时间函数，只显示年月日
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 设置表格单元格class
const tableCellClassName = () => {
  return 'compact-cell'
}

onMounted(async () => {
  try {
    // 获取总作品数
    const response = await request.get('/photo/all')
    totalWorks.value = response.data.data.total_photos
  } catch (error) {
    console.error('获取总作品数失败:', error)
  }

  // 获取用户数
  try {
    const usersResponse = await request.get('/user/all')
    totalUsers.value = usersResponse.data.data.total_users
  } catch (error) {
    console.error('获取用户数失败:', error)
  }

  // 获取最新注册用户信息
  try {
    const newUsersResponse = await request.get('/user/new')
    // 假设用户数据也在 list 字段中，与评论接口结构类似
    if (newUsersResponse.data.data && newUsersResponse.data.data.list) {
      newUsers.value = Array.isArray(newUsersResponse.data.data.list) 
        ? newUsersResponse.data.data.list.map(user => ({
            avatar: user.avatar || '',
            nickname: user.nickname || '未知用户',
            register_time: user.create_time || user.register_time,
            status: user.status || 0
          }))
        : []
    } else if (Array.isArray(newUsersResponse.data.data)) {
      // 兼容直接返回数组的情况
      newUsers.value = newUsersResponse.data.data
    } else {
      newUsers.value = []
    }
  } catch (error) {
    console.error('获取最新注册用户失败:', error)
  }

  // 获取最新评论信息
  try {
    const newCommentsResponse = await request.get('/comment/latest')
    // 直接从 data 数组中获取评论数据
    if (Array.isArray(newCommentsResponse.data.data)) {
      newComments.value = newCommentsResponse.data.data.map(item => ({
        avatar: item.user?.avatar || '',
        username: item.user?.nickname || '未知用户',
        content: item.content,
        create_time: item.create_time
      }))
    } else {
      newComments.value = []
    }
  } catch (error) {
    console.error('获取最新评论失败:', error)
  }

  // 获取作品分类占比
  try {
    const res = await request.get('/photo/category/stats')
    categoryStats.value = res.data.data || []
  } catch (error) {
    console.error('获取作品分类占比失败:', error)
  }

  // 获取其他信息（待审核作品、已发布作品、已下架作品、举报内容等）
  try {
    const manageResponse = await request.get('/photo/status/total')
    const { data } = manageResponse.data
    pendingWorks.value = data.pendingWorks  // 审核中(status=0)的作品
    publishedWorks.value = data.publishedWorks  // 已发布(status=1)的作品
    removedWorks.value = data.removedWorks  // 已封禁(status=2)的作品
    reportedContent.value = data.reportedContent
  } catch (error) {
    console.error('获取管理数据失败:', error)
  }
})
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  padding: 36px 28px;
  background: linear-gradient(145deg, #111827 0%, #1f2937 100%);
  color: #f3f4f6;
  max-width: 1400px;
  margin: 0 auto;
}

/* 亮色主题样式 */
.light-theme {
  --bg-gradient-start: #f9fafb;
  --bg-gradient-end: #f3f4f6;
  --card-bg: #ffffff;
  --text-primary: #111827;
  --text-secondary: #4b5563;
  --border-color: #e5e7eb;
  --card-shadow: 0 4px 24px 0 rgba(0,0,0,0.05);
}

.light-theme.dashboard-container {
  background: linear-gradient(145deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%);
  color: var(--text-primary);
}

.light-theme .overview-row,
.light-theme .manage-row,
.light-theme .chart-row,
.light-theme .recent-row {
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 24px;
  margin-bottom: 32px;
}

.light-theme .chart-card,
.light-theme .recent-card {
  background: var(--card-bg);
  box-shadow: var(--card-shadow);
  border: 1px solid var(--border-color);
}

.light-theme .chart-title,
.light-theme .recent-title {
  color: var(--text-primary);
}

.light-theme .recent-user {
  color: var(--text-primary);
}

.light-theme .recent-time {
  color: #3b82f6;
}

/* 暗色主题样式 */
.overview-row,
.manage-row,
.chart-row,
.recent-row {
  border-bottom: 1px solid rgba(255,255,255,0.08);
  padding-bottom: 16px;
  margin-bottom: 24px;
}

.stat-card, .manage-card, .chart-card, .recent-card {
  border-radius: 16px;
  margin-bottom: 28px;
  box-shadow: 0 8px 30px 0 rgba(0, 0, 0, 0.12);
  padding: 24px;
  background: #fff;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.stat-card, .manage-card {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.stat-card:hover, .manage-card:hover, .chart-card:hover, .recent-card:hover {
  box-shadow: 0 12px 40px 0 rgba(0, 0, 0, 0.18);
  transform: translateY(-4px);
}

/* 统计卡片样式 */
.stat-card {
  position: relative;
  overflow: hidden;
  height: 120px;
}

.stat-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  border-radius: 12px;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.primary-gradient {
  background: linear-gradient(135deg, #3b82f6, #6366f1);
}

.primary-gradient .stat-icon {
  background: rgba(255, 255, 255, 0.2);
}

.success-gradient {
  background: linear-gradient(135deg, #10b981, #059669);
}

.success-gradient .stat-icon {
  background: rgba(255, 255, 255, 0.2);
}

.stat-info {
  color: white;
}

.stat-card .stat-value {
  font-size: 2.4rem;
  font-weight: 700;
  line-height: 1.2;
  margin-bottom: 4px;
}

.stat-card .stat-label {
  font-size: 1rem;
  opacity: 0.8;
}

/* 管理卡片样式 */
.manage-card {
  position: relative;
  height: 100px;
}

.manage-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  border-radius: 10px;
  margin-right: 16px;
  font-size: 22px;
}

.review-card .manage-icon {
  background: #eef2ff;
  color: #6366f1;
}

.publish-card .manage-icon {
  background: #ecfdf5;
  color: #10b981;
}

.ban-card .manage-icon {
  background: #fef2f2;
  color: #ef4444;
}

.manage-value {
  font-size: 2.2rem;
  font-weight: 700;
  color: #111827;
  line-height: 1.2;
}

.manage-title {
  font-size: 1rem;
  color: #6b7280;
  margin-bottom: 8px;
}

/* 图表色彩柔和统一 */
.bar {
  background: linear-gradient(180deg, #B794F4 0%, #63B3ED 100%);
}
.pie-demo svg circle:nth-child(1) { stroke: #B794F4; }
.pie-demo svg circle:nth-child(2) { stroke: #63B3ED; }
.pie-demo svg circle:nth-child(3) { stroke: #F6AD55; }

/* 图表卡片包裹感 */
.chart-card {
  background: #fff;
  border-radius: 22px;
  box-shadow: 0 4px 24px 0 rgba(80, 80, 120, 0.10);
  padding: 24px 20px 20px 24px;
}

/* 按钮统一 */
:deep(.el-button) {
  border-radius: 8px !important;
  font-size: 1rem;
  font-weight: 500;
  box-shadow: 0 2px 8px 0 rgba(155,77,202,0.08);
  transition: box-shadow 0.2s;
}
:deep(.el-button:hover) {
  box-shadow: 0 4px 16px 0 rgba(155,77,202,0.15);
}

/* 评论和用户卡片字体缩小 */
.recent-user, .recent-title {
  font-size: 1.1rem;
  font-weight: 600;
  width: 100%;
  text-align: left;
  margin-bottom: 16px;
}
.recent-content, .recent-time {
  font-size: 0.95rem;
}

/* 响应式最大宽度与自适应 */
@media (max-width: 1500px) {
  .dashboard-container {
    max-width: 100%;
    padding: 16px 4px;
  }
}

@media (max-width: 768px) {
  .recent-card {
    margin-bottom: 20px;
  }
  
  .content-text {
    max-width: 150px;
  }
  
  .dashboard-container {
    padding: 16px 8px;
  }
  
  :deep(.el-table td), :deep(.el-table th) {
    padding: 8px 0;
  }
  
  .chart-card {
    margin-bottom: 20px;
  }
  
  .chart-row .el-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 576px) {
  .content-text {
    max-width: 100px;
  }
  
  .stat-card .stat-value {
    font-size: 1.8rem;
  }
  
  .manage-value {
    font-size: 1.6rem;
  }
  
  .recent-title, .chart-title {
    font-size: 1rem;
  }
  
  :deep(.el-table .cell) {
    padding-left: 5px;
    padding-right: 5px;
  }
  
  .pie-chart svg {
    width: 140px;
    height: 140px;
  }
}

/* 暗色主题下卡片背景和字体 */
.dashboard-container:not(.light-theme) .stat-card,
.dashboard-container:not(.light-theme) .manage-card,
.dashboard-container:not(.light-theme) .chart-card,
.dashboard-container:not(.light-theme) .recent-card {
  background: #23262F;
  color: #fff;
  border: 1px solid #23262F;
}

.dashboard-container:not(.light-theme) .stat-card .stat-label,
.dashboard-container:not(.light-theme) .manage-title,
.dashboard-container:not(.light-theme) .chart-title,
.dashboard-container:not(.light-theme) .recent-title,
.dashboard-container:not(.light-theme) .bar-label,
.dashboard-container:not(.light-theme) .pie-legend,
.dashboard-container:not(.light-theme) .recent-content {
  color: #bfcbd9;
}

.dashboard-container:not(.light-theme) .recent-user,
.dashboard-container:not(.light-theme) .stat-card .stat-value,
.dashboard-container:not(.light-theme) .manage-value {
  color: #fff;
}

.dashboard-container:not(.light-theme) .recent-title,
.dashboard-container:not(.light-theme) .manage-title,
.dashboard-container:not(.light-theme) .chart-title {
  color: #fff;
  font-weight: 600;
}

.dashboard-container:not(.light-theme) :deep(.el-table) {
  --el-table-border-color: #363b48;
  --el-table-header-bg-color: #2c3039;
  --el-table-row-hover-bg-color: #363b48;
  --el-table-text-color: #e0e0e0;
  background-color: #23262F;
  color: #e0e0e0;
  border-color: #363b48;
}

.dashboard-container:not(.light-theme) :deep(.el-table td),
.dashboard-container:not(.light-theme) :deep(.el-table th.is-leaf) {
  border-bottom: 1px solid #363b48;
}

/* 表头居中 */
:deep(.el-table th) {
  text-align: center;
}

.dashboard-container:not(.light-theme) :deep(.el-table--border) {
  border: 1px solid #363b48;
}

.dashboard-container:not(.light-theme) :deep(.el-table__cell) {
  background-color: #23262F;
}

/* 确保表格内的文字颜色适应主题 */
.dashboard-container:not(.light-theme) :deep(.el-table .cell) {
  color: #e0e0e0;
}

.chart-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #111827;
  margin-bottom: 16px;
  margin-top: 0;
}

.pie-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
  padding: 0 8px 16px;
  flex-wrap: wrap;
}

@media (max-width: 1200px) {
  .pie-container {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .pie-container {
    flex-direction: column;
    align-items: center;
  }
  
  .pie-chart {
    margin-bottom: 20px;
  }
  
  .pie-legend {
    width: 100%;
    max-width: 320px;
  }
}

.pie-chart {
  display: flex;
  justify-content: center;
  position: relative;
}

.pie-segment {
  transition: all 0.3s ease;
}

.pie-segment:hover {
  opacity: 0.8;
  transform: scale(1.02);
}

.pie-legend {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.color-dot {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 3px;
}

.category-name {
  flex: 1;
  color: #4b5563;
}

.category-percent {
  font-weight: 600;
  color: #111827;
}

.no-data {
  color: #9ca3af;
  font-style: italic;
}

/* 表格现代化样式 */
.modern-table {
  --el-table-border-color: #e5e7eb;
  --el-table-header-bg-color: #f9fafb;
  --el-table-row-hover-bg-color: #f3f4f6;
  border-radius: 12px;
  overflow: hidden;
  margin-top: 8px;
  width: 100%;
  table-layout: fixed;
}

.dashboard-container:not(.light-theme) .modern-table {
  --el-table-border-color: #374151;
  --el-table-header-bg-color: #1f2937;
  --el-table-row-hover-bg-color: #374151;
  --el-table-text-color: #e5e7eb;
}

.dashboard-container:not(.light-theme) .pie-chart circle:first-child {
  fill: #1f2937;
}

.table-avatar {
  border: 2px solid #e5e7eb;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.username-cell {
  font-weight: 600;
  color: #111827;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dashboard-container:not(.light-theme) .username-cell {
  color: #e5e7eb;
}

.content-cell {
  padding: 4px 0;
}

.content-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #6b7280;
  font-size: 12px;
  white-space: nowrap;
}

.status-tag {
  border-radius: 12px;
  padding: 0 8px;
  font-weight: 500;
}

.recent-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #111827;
  margin-bottom: 16px;
  margin-top: 0;
  text-align: left;
  display: block;
  width: 100%;
}

.dashboard-container:not(.light-theme) .recent-title {
  color: #f3f4f6;
}

.recent-card {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  height: 100%;
}

:deep(.el-table) {
  max-width: 100%;
  overflow-x: auto;
}

:deep(.el-table .cell) {
  word-break: keep-all;
  white-space: nowrap;
}

:deep(.el-table--fit) {
  width: 100%;
}

:deep(.el-table--enable-row-transition .el-table__body td) {
  transition: background-color 0.25s ease;
}
</style>
